﻿using MediatR;
using MyRabbit.Application.Command.ImmuneCommand;
using MyRabbit.Application.Dtos;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler.ImmuneCommandHandler
{
    public class ImmuneQueryCommandHandler : IRequestHandler<ImmuneQueryCommand, APIResult<List<ImmuneDTO>>>
    {

        private readonly IRepository<Immune> immRep;
        private readonly IRepository<BreedImmune> breedimmRep;
        public ImmuneQueryCommandHandler(IRepository<Immune> immRep, IRepository<BreedImmune> breedimmRep)
        {
            this.immRep = immRep;
            this.breedimmRep = breedimmRep;
        }

        public async Task<APIResult<List<ImmuneDTO>>> Handle(ImmuneQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ImmuneDTO>> result=new APIResult<List<ImmuneDTO>>();
            
            try
            {
                result.Code = Codes.查询成功;
                result.Message = Codes.查询成功.ToString();
                var list = from a in await immRep.GetAllAsync()
                           join b in await breedimmRep.GetAllAsync() on a.ImmuneId equals b.ImmuneId
                           where b.BreedId == request.BreedId
                           select new ImmuneDTO
                           {
                               ImmuneId = a.ImmuneId,
                               FeedingDays = a.FeedingDays,
                               ImmunityType = a.ImmunityType,
                               ImmunityMethod = a.ImmunityMethod,
                           };
                result.Data = list.ToList();
            }
            catch (Exception ex)
            {
                result.Code = Codes.查询失败;
                result.Message = Codes.查询失败.ToString() + ex.Message;
                return await Task.FromResult(result);
            }
            return await Task.FromResult(result);
            
        }
    }
}
